package com.laicunba.ext.web.controller.h5.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.service.SlaveRegistryService;
import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.VcoinWalletService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;
 
//@Controller
@RequestMapping(value = "/h5/ext/activity")
public class KillTheDragonController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(KillTheDragonController.class);
	@Autowired
	private RegistryService registryService;
	@Autowired
	private UserService userService;
	@Autowired
	private SlaveUserService slaveUserService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private SlaveActivityJoinService slaveActivityJoinService;
	@Autowired
	private VcoinWalletService vcoinWalletService;
	@Autowired
	private SlaveRegistryService slaveRegistryService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/kill_the_dragon.htm")
	public ModelAndView killTheDragon(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("kill_the_dragon.jsp");
		try {
			
			Map<String, Object> tempMap = null;
			final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<Map<String, Object>> actJoinList = slaveActivityJoinService.findActivityJoinList("20170424", "013", null, 20);
			RegistryDO actDataRegistry = registryService.get(RegistryDO.class, "sys.act.data.20170424");
			if (actJoinList != null && actDataRegistry != null && StringUtil.isNotEmpty(actDataRegistry.getVal())) {
				JSONArray registryActJoinArray = (JSONArray) new JSONParser().parse(actDataRegistry.getVal());
				if (registryActJoinArray != null && registryActJoinArray.size() > 0) {
					for (int i = 0; i < registryActJoinArray.size(); i++) {
						tempMap = (Map<String, Object>) registryActJoinArray.get(i);
						actJoinList.add(tempMap);
					}
					Collections.sort(actJoinList, new Comparator<Map<String, Object>>() {
						public int compare(Map<String, Object> m1, Map<String, Object> m2) {
							Date date1 = null;
							Date date2 = null;
							try {
								date1 = sdf.parse(String.valueOf(m1.get("gmt_create")));
								date2 = sdf.parse(String.valueOf(m2.get("gmt_create")));
							} catch (Exception e) {
								e.printStackTrace();
							}
							
							if (date1.compareTo(date2) > 0) {
								return -1;
							} else {
								return 1;
							}
						}
					});
				}
			}
			view.addObject("actJoinList", actJoinList);
			
			UserDO loginUser = getCurrentUser(request);
			if(loginUser != null) {
				//清理老活动的累积积分，如果已清理则不再次进行
				RegistryDO cleanInviteVcoinRegistry = registryService.get(RegistryDO.class, "u." + loginUser.getId() + ".clean-dragon-vcoin");
				if(cleanInviteVcoinRegistry == null) {
					long balance = vcoinWalletService.getBalance(loginUser.getId());
					if(balance > 0) {
						vcoinWalletService.subtract(loginUser.getId(), (int) balance, "KILL_THE_DRAGON_ACT", "屠龙活动积分清零");
					}
					
					cleanInviteVcoinRegistry = new RegistryDO();
					cleanInviteVcoinRegistry.setId("u." + loginUser.getId() + ".clean-dragon-vcoin");
					cleanInviteVcoinRegistry.setVal(String.valueOf(balance));
					cleanInviteVcoinRegistry.setVisible(true);
					cleanInviteVcoinRegistry.setSummary("屠龙活动清除老活动的累积积分");
					registryService.create(cleanInviteVcoinRegistry);
				}
	
				view.addObject("loginStatus", "1");
				view.addObject("vcoinBalance", vcoinWalletService.getBalance(loginUser.getId()));
				String chanceKey = "act.20170424chance." + loginUser.getId() + DateUtil.formatDate(new Date());
				String cjCountKey = "act.20170424CJ." + loginUser.getId() + DateUtil.formatDate(new Date());
				int todayHitEggsChance = StringUtil.isNotEmpty(CacheUtil.getAttribute(chanceKey)) ? Integer.parseInt(CacheUtil.getAttribute(chanceKey)) : 0 ;
				int todayHitEggsCount = StringUtil.isNotEmpty(CacheUtil.getAttribute(cjCountKey)) ? Integer.parseInt(CacheUtil.getAttribute(cjCountKey)) : 0 ;
				if(todayHitEggsChance > 0 && todayHitEggsCount >=0) {
					view.addObject("hitEggsChance", todayHitEggsChance - todayHitEggsCount);
				} else {
					view.addObject("hitEggsChance", 0);
				}
				
				RegistryDO killProgress = registryService.get(RegistryDO.class, "act.kill-dragon." + loginUser.getId() + ".progress");
				if(killProgress != null) {
					view.addObject("killProgress", killProgress.getVal());
				} else {
					view.addObject("killProgress", 0);
				}
				
				view.addObject("killDragonRank", slaveRegistryService.findKillDragonRank(loginUser.getId()));
				
				List<Map<String, Object>> userRewardData = slaveActivityJoinService.findUserRewardData("20170424", loginUser.getId());
				if(userRewardData != null && userRewardData.size() > 0) {
					for (Map<String, Object> map : userRewardData) {
						if(map.containsKey("reward_type") && map.containsKey("reward_count")) {
							if("red_package".equalsIgnoreCase((String) map.get("reward_type"))) {
								view.addObject("redPackageCount", map.get("reward_count"));
							} else if("jd_e_card".equalsIgnoreCase((String) map.get("reward_type"))) {
								view.addObject("jdECardCount", map.get("reward_count"));
							} else if("phone_fee".equalsIgnoreCase((String) map.get("reward_type"))) {
								view.addObject("phoneFeeCount", map.get("reward_count"));
							}
						}
					}
				}
				
				view.addObject("myActJoinList", slaveActivityJoinService.findActivityJoinList("20170424", null, loginUser.getId(), 100));
			} else {
				view.addObject("loginStatus", "0");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/kill_dragon_login_status.htm")
	public String gainGoldGoInvite(HttpServletRequest request){
		JSONObject json = new JSONObject();
		UserDO user = getCurrentUser(request);
		if(user == null) {
			json.put("loginStatus", 0);
		} else {
			json.put("loginStatus", 1);
		}
		return json.toJSONString();
	}

}
